package com.jianyun.jyzs.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jianyun.jyzs.R;
import com.jianyun.jyzs.adapter.EngineerAttachGridViewAdapter;
import com.jianyun.jyzs.bean.BaseResult;
import com.jianyun.jyzs.bean.EngineeringResult;
import com.jianyun.jyzs.constant.SysConstant;
import com.jianyun.jyzs.dao.EngineerDao;
import com.jianyun.jyzs.http.Api;
import com.jianyun.jyzs.http.CustomCallback;
import com.jianyun.jyzs.http.EngineerHttpHelper;
import com.jianyun.jyzs.http.RetrofitHelper;
import com.jianyun.jyzs.utils.DateTime;
import com.jianyun.jyzs.utils.DensityUtil;
import com.jianyun.jyzs.utils.LoginCache;
import com.jianyun.jyzs.utils.Utils;
import com.jianyun.jyzs.utils.UtilsStyle;
import com.jianyun.jyzs.widget.CircleMovementMethod;
import com.jianyun.jyzs.widget.ExpandGridView;
import com.jianyun.jyzs.widget.LineBreakLayout;
import com.jianyun.jyzs.widget.PasteEditText;
import com.jianyun.jyzs.widget.PromptDialog;
import com.jianyun.jyzs.widget.SpannableClickable;
import com.jrmf360.rylib.common.util.ToastUtil;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import com.jianyun.jyzs.utils.RceLog;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 工程动态详情
 * Created by mlli on 2017/11/13.
 */

public class EngDetialActivity extends AppCompatActivity implements View.OnClickListener {

    @BindView(R.id.topBack)
    ImageView topBack;
    @BindView(R.id.topText)
    TextView topText;
    @BindView(R.id.tv_checked)
    TextView tvChecked;
    @BindView(R.id.tv_update)
    TextView tvUpdate;
    @BindView(R.id.iv_more)
    ImageView ivMore;
    @BindView(R.id.iv_moreLinearLayout)
    LinearLayout ivMoreLinearLayout;
    @BindView(R.id.topCreat)
    LinearLayout topCreat;
    @BindView(R.id.iv_single)
    ImageView ivSingle;
    @BindView(R.id.iv_group)
    ImageView ivGroup;
    @BindView(R.id.topChatDetail)
    LinearLayout topChatDetail;
    @BindView(R.id.topId)
    RelativeLayout topId;
    @BindView(R.id.head)
    ImageView head;
    @BindView(R.id.headParent)
    LinearLayout headParent;
    @BindView(R.id.headName)
    TextView headName;
    @BindView(R.id.tv_type)
    TextView tvType;
    @BindView(R.id.hot)
    TextView hot;
    @BindView(R.id.tv_text)
    TextView tvText;
    @BindView(R.id.gv_gridView)
    ExpandGridView gvGridView;
    @BindView(R.id.tv_projectName)
    TextView tvProjectName;
    @BindView(R.id.tv_projectLoc)
    TextView tvProjectLoc;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_delete)
    TextView tvDelete;
    @BindView(R.id.iv_agree)
    ImageView ivAgree;
    @BindView(R.id.iv_discuss)
    ImageView ivDiscuss;
    @BindView(R.id.ll_agree)
    LineBreakLayout llAgree;
    @BindView(R.id.ll_c_agree)
    LinearLayout llCAgree;
    @BindView(R.id.ll_discuss)
    LinearLayout llDiscuss;
    @BindView(R.id.ll_c_bg)
    LinearLayout llCBg;
    @BindView(R.id.et_sendmessage)
    PasteEditText etSendmessage;
    @BindView(R.id.btn_send)
    Button btnSend;
    @BindView(R.id.ll_toDiscuss)
    LinearLayout llToDiscuss;
    private EngineerDao dao;
    private Gson gson;
    private String enterpriseCode;
    private EngDetialActivity context;
    public String userid;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        UtilsStyle.setStatusBarMode(this,true);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.engineer_detial);
        ButterKnife.bind(this);
        init();
    }


    protected void init() {
        context = this;
        topBack.setVisibility(View.VISIBLE);
        topBack.setOnClickListener(this);
        topText.setText("动态详情");
        initData();
    }

    private void initData() {
        enterpriseCode = LoginCache.getInstance().getLoginCache().getEnterpriseCode();
        userid = LoginCache.getInstance().getUserInfo().getUserId();
        gson = new Gson();
        String eid = getIntent().getStringExtra(SysConstant.msg_key_string1);
        dao = new EngineerDao(this);
        EngineeringResult.EngineerBean bean = dao.getEngineerByid(eid, enterpriseCode);
        btnSend.setOnClickListener(this);
        initView(bean);
    }

    private void initView(final EngineeringResult.EngineerBean bean) {
        headName.setText(wipeStr(bean.getUserName()));
        if (bean.getType() == null) {
            tvType.setVisibility(View.INVISIBLE);
        } else {
            tvType.setVisibility(View.VISIBLE);
            tvType.setText(bean.getType());
        }
        tvText.setText(bean.getTextStr());
        final String userId = bean.getUserId();
        tvProjectName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                context.startActivity(new Intent(context, EngineerProjectDetialActivity.class).putExtra(SysConstant.msg_key_string1, bean.getProjectId()));
            }
        });
        tvProjectLoc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                context.startActivity(new Intent(context, EngineerProjectDetialActivity.class).putExtra(SysConstant.msg_key_string1, bean.getProjectId()));
            }
        });
        head.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (userId.equals(bean.getUserId())) {
                    //自己
                    context.startActivity(new Intent(context, PersonalDyamicActivity.class));
                } else {
                    context.startActivity(new Intent(context, OthersDyamicActivity.class).putExtra(SysConstant.msg_key_string1, bean.getUserId()));
                }
            }
        });
        headName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (userId.equals(bean.getUserId())) {
                    //自己
                    context.startActivity(new Intent(context, PersonalDyamicActivity.class));
                } else {
                    context.startActivity(new Intent(context, OthersDyamicActivity.class).putExtra(SysConstant.msg_key_string1, bean.getUserId()));
                }
            }
        });
        ivAgree.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                /**
                 * TODO 待完成
                 */
                EngineerHttpHelper.agree(dao, bean.getProjectId(), bean.getId(), new EngineerHttpHelper.AgreeResult() {
                    @Override
                    public void agreeResult(boolean b, String msg, List<EngineeringResult.EngineerBean.AgressBean> list) {
                        if (b) {
                            setAgressView(llCBg, llCAgree, llAgree, list);
                        } else {
                            ToastUtil.showNoWaitToast(context, msg);
                        }
                    }
                });
            }
        });
        disArgs.put("projectId", bean.getProjectId());
        disArgs.put("projectProgressId", bean.getId());
        ivDiscuss.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                disArgs.put("projectId", bean.getProjectId());
                disArgs.put("projectProgressId", bean.getId());
                openKeybord(bean.getUserName());
            }
        });
        String photo = bean.getPhoto();
        String url=LoginCache.getInstance().getLoginCache().getErpRootUrl()+photo;
        Glide.with(context).load(url).into(head);

        Type attachtype = new TypeToken<List<EngineeringResult.EngineerBean.AttachmentBean>>() {
        }.getType();
        Type agresshtype = new TypeToken<List<EngineeringResult.EngineerBean.AgressBean>>() {
        }.getType();
        Type discusstype = new TypeToken<List<EngineeringResult.EngineerBean.DiscussBean>>() {
        }.getType();
        Type images = new TypeToken<ArrayList<String>>() {
        }.getType();
        List<EngineeringResult.EngineerBean.DiscussBean> discusslist = gson.fromJson(bean.getListDisscuss(), discusstype);
        List<EngineeringResult.EngineerBean.AttachmentBean> attachmentlist = gson.fromJson(bean.getListAttachment(), attachtype);
        List<EngineeringResult.EngineerBean.AgressBean> agresslist = gson.fromJson(bean.getListAgress(), agresshtype);
        ArrayList<String> imageList = gson.fromJson(bean.getListImages(), images);

        if (attachmentlist != null && attachmentlist.size() > 0) {

            EngineerAttachGridViewAdapter engineerAttachGridViewAdapter = new EngineerAttachGridViewAdapter(context, attachmentlist, imageList);
            if (attachmentlist.size() == 1) {
                LinearLayout.LayoutParams lp0 = new LinearLayout.LayoutParams(DensityUtil.dip2px(context, 165), ViewGroup.LayoutParams.WRAP_CONTENT);
                gvGridView.setLayoutParams(lp0);
                gvGridView.setNumColumns(1);
            } else {
                LinearLayout.LayoutParams lp0 = new LinearLayout.LayoutParams(DensityUtil.dip2px(context, 246), ViewGroup.LayoutParams.WRAP_CONTENT);
                gvGridView.setLayoutParams(lp0);
                gvGridView.setNumColumns(3);
            }
            gvGridView.setAdapter(engineerAttachGridViewAdapter);
        } else {
            gvGridView.setVisibility(View.GONE);
        }
        tvTime.setText(DateTime.getFriendlytime(new Date(bean.getDtLong())));
        //String currentUserid = CacheTask.getInstance().getUserId();
        if (userid.equals(userId)) {
            tvDelete.setVisibility(View.VISIBLE);
            tvDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    //此动态是本人发布 可删除
                    delEngineer(bean.getId());
                }
            });
        } else {
            tvDelete.setVisibility(View.GONE);
        }
        tvProjectName.setText(bean.getProjectName());
        tvProjectLoc.setText(bean.getPlace() == null ? "" : "." + bean.getPlace());
        llCBg.setVisibility(View.GONE);//先让评论和点赞去隐藏
        setAgressView(llCBg, llCAgree, llAgree, agresslist);
        setDiscussView(llCBg, llDiscuss, discusslist, bean);
    }


    //保存评论的参数
    HashMap<String, String> disArgs = new HashMap<>();
    LinearLayout linearLayout;

    //设置评论的显示
    private void setDiscussView(LinearLayout llCBg, LinearLayout llDiscuss, List<EngineeringResult.EngineerBean.DiscussBean> discusslist, final EngineeringResult.EngineerBean bean) {
        if (discusslist.size() == 0) {
            llDiscuss.setVisibility(View.GONE);
        } else {
            llCBg.setVisibility(View.VISIBLE);
            llDiscuss.setVisibility(View.VISIBLE);
            llDiscuss.removeAllViews();
            final CircleMovementMethod circleMovementMethod = new CircleMovementMethod(R.color.ppdiscussselect, R.color.ppdiscussselect);
            for (final EngineeringResult.EngineerBean.DiscussBean eed : discusslist) {
                linearLayout = processLinearLayout();
                TextView textview = null;
                if (eed.getToUserId() == null||TextUtils.isEmpty(eed.getToUserId())) {//对于当前动态的评论
                    SpannableStringBuilder builder = new SpannableStringBuilder();
                    builder.append(setClickableSpan(eed.getFromUserName(), eed.getFromUserId()));
                    builder.append(":" + eed.getTextStr());
                    textview = processTextView(builder, R.color.content1);
                    textview.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            if (circleMovementMethod.isPassToTv()) {
                                disArgs.put("toUserId", eed.getFromUserId());
                                disArgs.put("toUserName", eed.getFromUserName());
                                disArgs.put("projectId", bean.getProjectId());
                                disArgs.put("projectProgressId", bean.getId());
                                openKeybord(eed.getFromUserName());
                            }
                        }
                    });
                    textview.setMovementMethod(circleMovementMethod);
                    linearLayout.addView(textview);
                } else {//对于某人评论的回应
                    SpannableStringBuilder builder = new SpannableStringBuilder();
                    builder.append(setClickableSpan(eed.getFromUserName(), eed.getFromUserId()));
                    builder.append("  回复 ");
                    builder.append(setClickableSpan(eed.getToUserName(), eed.getToUserId()));
                    builder.append(":" + eed.getTextStr());
                    textview = processTextView(builder, R.color.content1);
                    textview.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Log.i("test","点击2");
                            if (circleMovementMethod.isPassToTv()) {
                                disArgs.put("toUserId", eed.getFromUserId());
                                disArgs.put("toUserName", eed.getFromUserName());
                                disArgs.put("projectId", bean.getProjectId());
                                disArgs.put("projectProgressId", bean.getId());
                                openKeybord(eed.getFromUserName());
                            }
                        }
                    });
                    textview.setMovementMethod(circleMovementMethod);
                    linearLayout.addView(textview);
                }
                llDiscuss.addView(linearLayout);
            }
        }
    }

    private String wipeStr(String str) {
        String substring = str;
        if (str.endsWith(",")) {
            substring = str.substring(0, str.length() - 1);
        }
        return substring;
    }

    //设置评论的水平布局
    public LinearLayout processLinearLayout() {
        LinearLayout linearLayout = new LinearLayout(context);
        LinearLayout.LayoutParams lp0 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        linearLayout.setOrientation(LinearLayout.HORIZONTAL);
        linearLayout.setLayoutParams(lp0);
        return linearLayout;
    }

    private void delEngineer(final String id) {
        PromptDialog dialog = PromptDialog.newInstance(context, "确定删除？", "");
        dialog.setPromptButtonClickedListener(new PromptDialog.OnPromptButtonClickedListener() {
            @Override
            public void onPositiveButtonClicked() {
                HashMap<String, String> map = new HashMap<>();
                map.put("method","deleteProjectProgress");
                map.put("userId", userid);
                map.put("enterpriseCode", enterpriseCode);
                map.put("progressId", id);
                map.put("appCode", "jyzs");
                map.put("appType", "Android");
                map.put("appVersion", "1.0.2");
                Api api = RetrofitHelper.builderCeshiHttp().create(Api.class);
                api.delNewEngineer(map).observeOn(AndroidSchedulers.mainThread())
                        .subscribeOn(Schedulers.io())
                        .subscribe(new CustomCallback<BaseResult>() {
                            @Override
                            protected void onResponse(BaseResult response) {
                                RceLog.i("lml", response.toString());
                                if (response.isResult() == true) {
                                    //删除成功 移除item 移除本地数据库数据
                                    dao.delEngineer(id);
                                    finishab();
                                } else {
                                    ToastUtil.showNoWaitToast(context, response.getMessage());
                                }
                            }

                            @Override
                            protected void onException(String msg) {
                                ToastUtil.showNoWaitToast(context, msg);
                            }
                        });
            }

            @Override
            public void onNegativeButtonClicked() {

            }
        });
        dialog.show();

    }

    public void finishab(){
        setResult(20);
        finish();
    }


    //生成评论人显示文本
    private SpannableString setClickableSpan(final String name, final String id) {
        SpannableString subjectSpanText = new SpannableString(wipeStr(name));
        subjectSpanText.setSpan(new SpannableClickable() {
                                    @Override
                                    public void onClick(View widget) {
                                        //点击进入评论人动态界面
                                       // ToastUtil.showNoWaitToast(context, "进入个人页面");
//                                        context.startActivity(new Intent(context,ProjectProgressDetailActivity.class).putExtra(SysConstant.msg_key_string1, id));
                                    }

                                    @Override
                                    public void updateDrawState(TextPaint ds) {
                                        super.updateDrawState(ds);
                                        ds.setColor(0xff2869AD);
                                        ds.setUnderlineText(false);
                                    }
                                }, 0, subjectSpanText.length(),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        return subjectSpanText;
    }

    private void openKeybord(String hint) {
        hint = wipeStr(hint);
        //设置可获得焦点
        etSendmessage.setFocusable(true);
        etSendmessage.setFocusableInTouchMode(true);
        //请求获得焦点
        etSendmessage.requestFocus();
        etSendmessage.setHint("回复" + hint + ":");
        //调用系统输入法
        InputMethodManager inputManager = (InputMethodManager) etSendmessage.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.showSoftInput(etSendmessage, 0);
    }

    //设置点赞的显示
    private void setAgressView(LinearLayout llCBg, LinearLayout llCAgree, LineBreakLayout llAgree, List<EngineeringResult.EngineerBean.AgressBean> agresslist) {
        if (agresslist.size() > 0) {
            llCBg.setVisibility(View.VISIBLE);
            llCAgree.setVisibility(View.VISIBLE);
            llAgree.removeAllViews();
            int index = 1;
            for (final EngineeringResult.EngineerBean.AgressBean agree : agresslist) {
                TextView textview = null;
                if (index == agresslist.size()) {
                    textview = processTextView((index == 1 ? "  " : "") + wipeStr(agree.getUserName()), R.color.ppdiscuss);
                } else {
                    textview = processTextView((index == 1 ? "  " : "") + wipeStr(agree.getUserName()) + "、", R.color.ppdiscuss);
                }
                textview.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ToastUtil.showNoWaitToast(context, "进入个人动态详情界面" + agree.getUserName());
                    }
                });
                llAgree.addView(textview);
                index++;
            }
        } else {
            llCAgree.setVisibility(View.GONE);
        }
    }

    public TextView processTextView(String value, int color) {
        TextView tv = new TextView(context);
        tv.setText(value);
        tv.setTextSize(14);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        tv.setLayoutParams(params);
        tv.setTextColor(context.getResources().getColor(color));
        tv.setGravity(Gravity.LEFT | Gravity.CENTER);
        tv.setHighlightColor(context.getResources().getColor(android.R.color.transparent));
//		tv.setId(id);
        return tv;
    }

    public TextView processTextView(SpannableStringBuilder value, int color) {
        TextView tv = new TextView(context);
        tv.setText(value);
        tv.setTextSize(14);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        tv.setLayoutParams(params);
        tv.setTextColor(context.getResources().getColor(color));
        tv.setGravity(Gravity.LEFT | Gravity.CENTER);
        tv.setHighlightColor(context.getResources().getColor(android.R.color.transparent));
//		tv.setId(id);
        return tv;
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_send:
                String trim = etSendmessage.getText().toString().trim();
                if (!TextUtils.isEmpty(trim)) {
                    sendDiscuss(trim);
                    etSendmessage.setText(null);
                    Utils.closeKeyBoard(context, btnSend);
                } else {
                    ToastUtil.showNoWaitToast(context, "评论不可为空");
                }
                break;
            case R.id.topBack:
                finish();
                break;
        }
    }

    //发出评论消息
    public void sendDiscuss(String text) {
        disArgs.put("text", text);

        EngineerHttpHelper.discuss(dao, disArgs, disArgs.get("projectProgressId"), new EngineerHttpHelper.DiscussResult() {
            @Override
            public void discussResult(boolean b, String msg, List<EngineeringResult.EngineerBean.DiscussBean> list) {
                if (b) {
                    initData();
                } else {
                    ToastUtil.showNoWaitToast(context, msg);
                }
            }
        });
    }
}
